package com.epalmpay.service.thread;

import com.epalmpay.entity.ActivityUnroutineRule;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.mapper.ActivityBaseMapper;
import com.epalmpay.mapper.ActivityUnroutineRuleMapper;

import java.util.List;

public class CheckCouponActivityRuleThread implements Runnable {
    private String couponId;
    private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
    private ActivityBaseMapper activityBaseMapper;

    public CheckCouponActivityRuleThread(String couponId, ActivityUnroutineRuleMapper activityUnroutineRuleMapper,
                                         ActivityBaseMapper activityBaseMapper) {
        this.couponId = couponId;
        this.activityUnroutineRuleMapper = activityUnroutineRuleMapper;
        this.activityBaseMapper = activityBaseMapper;
    }

    @Override
    public void run() {
        List<ActivityUnroutineRule> activityUnroutineRules = activityUnroutineRuleMapper.listByRuleContainCouponId(couponId);
        for(int i = 0; i < activityUnroutineRules.size(); i++) {
            ActivityUnroutineRule activityUnroutineRule = activityUnroutineRules.get(i);
            if(activityUnroutineRule.getCouponId().equals(couponId)) {
                activityUnroutineRuleMapper.deleteByPrimaryKey(activityUnroutineRule.getId());
                int count = activityUnroutineRuleMapper.countRuleByActivityId(activityUnroutineRule.getActivityId());
                if(count == 0) {
                    activityBaseMapper.updateStatusByPrimaryKey(activityUnroutineRule.getActivityId(), ActivityEnum.ActivityStatus.Over.getType());
                }
            } else {
                String newCouponId = activityUnroutineRule.getCouponId().replace("," + couponId, "").replace(couponId + ",", "");
                activityUnroutineRule.setCouponId(newCouponId);
                activityUnroutineRuleMapper.updateByPrimaryKeySelective(activityUnroutineRule);
            }
        }
    }
}
